package controllers;

import java.util.List;

import models.Category;
import models.City;
import models.Product;
import models.User;
import models.ticket.Ticket;
import models.ticket.TicketMessage;

import org.mindrot.jbcrypt.BCrypt;

import play.data.DynamicForm;
import play.data.Form;
import play.data.validation.Constraints.Email;
import play.data.validation.Constraints.Required;
import play.mvc.Controller;
import play.mvc.Result;
import play.mvc.Security;
import views.html.admin.adminproduct;
import views.html.admin.adminproductedit;
import views.html.admin.adminuser;
import views.html.admin.adminuseredit;
import views.html.admin.admincategory;
import views.html.admin.parts.adminmain;


@Security.Authenticated(SecuredAdmin.class)
public class Admin extends Controller {
	
	public static Result index()
	{
		return ok(adminmain.render());
	}
	
	/*
	 * User Manager
	 * Author: Axakalov Sunnatilla
	 */

	public static Result user(int page, String sortBy, String order, String filter)
	{
		return ok(
				adminuser.render(User.page(page, 5, sortBy, order, filter),
						sortBy, order, filter));
	}
	
	public static Result userPage(Long id)
	{
		Form<UserForm> form = Form.form(UserForm.class);
		
		User user = User.find.byId(id);
		UserForm uf = new UserForm();
		uf.id = id;
		uf.username = user.username;
		uf.name = user.name;
		uf.surname = user.surname;
		uf.email = user.email;
		uf.city = user.city;
		uf.address = user.address;
		
		form = form.fill(uf);
		return ok(adminuseredit.render(form, City.find.all()));
	}
	
	public static Result updateUser(Long id)
	{
		Form<UserForm> form = Form.form(UserForm.class).bindFromRequest();
		User user = User.find.byId(id);
		UserForm uf = new UserForm();
		
//		if(form.hasErrors())
//		{ 
//			return badRequest(adminuseredit.render(form, City.find.all()));
//		}
		
		user.username = form.get().username;
		user.name = form.get().name;
		user.surname = form.get().surname;
		user.password = BCrypt.hashpw(form.get().password, BCrypt.gensalt());
		user.address = form.get().address;
		user.city = form.get().city;
		user.email = form.get().email;
		
//		user.role = form.get().role;
		
		uf.id = id;
		uf.username = user.username;
		uf.name = user.name;
		uf.surname = user.surname;
		uf.email = user.email;
		uf.city = user.city;
		uf.address = user.address;
		
		user.save();
		
		form = form.fill(uf);
		
		return ok(adminuseredit.render(form, City.find.all()));
	}
	
	public static Result newUser()
	{
		return ok();
	}
	
	public static Result deleteUser(Long id)
	{
		User.find.byId(id).delete();
		return redirect(routes.Admin.user(routes.Admin.user$default$1(),
				routes.Admin.user$default$2(), routes.Admin.user$default$3(),
				routes.Admin.user$default$4()));
	}
	
	public static class UserForm
	{
		public Long id;
		@Required
		public String username;
		
		public String name;
		public String surname;
		
		@Required
		@Email
		public String email;
		
		public String password;
		public String cpassword;
		
		public String city;
		public String address;
		
		public Integer role;
		
		public String validate()
		{
			if(!password.trim().equals(cpassword.trim()) || (password.equals("") && cpassword.equals("")))
			{
				return "Fill all required fields.";
			}
			return null;
		}
	}
	
	/*
	 * Categories
	 * Author: Khalmuratov Alisher
	 */
	
	public static Result category(Integer page)
	{
		return ok(admincategory.render(Category.page(page)));
	}
	
	public static Result categoryPage(Long id)
	{
		return ok();
	}
	
	public static Result updateCategory(Long id)
	{
		return ok();
	}
	
	public static Result newCategory()
	{
		DynamicForm form = Form.form().bindFromRequest();
		String name = form.get("name");
		Category category = Category.create(name, null);
		category.save();
		flash("success", "Category succesfully added");
		return ok(admincategory.render(Category.page(0)));
	}
	
	public static Result deleteCategory(Long id)
	{
		return ok();
	}
	
	/*
	 * Products
	 * Author: Talasbek Assem
	 */
	
	public static Result product(int page, String producer, String priceStart,
						String priceEnd, String sortBy, String order, String filter)
	{
		return ok(
				adminproduct.render(
						Product.page(page, 5, producer,	priceStart,
								priceEnd, sortBy, order, filter),
						producer, priceStart, priceEnd,
						sortBy, order, filter));
	}
	
	public static Result productPage(Long id)
	{
		Form<Product> form = Form.form(Product.class);
		form = form.fill(Product.find.byId(id));
		return ok(adminproductedit.render(form));
	}
	
	public static Result updateProduct(Long id)
	{
		Form<Product> form = Form.form(Product.class).bindFromRequest();
		if(form.hasErrors())
		{
			return badRequest(adminproductedit.render(form));
		}
		Product product = Product.find.byId(id);
		product.title = form.get().title;
		product.price = form.get().price;
		product.quantity = form.get().quantity;
		product.description = form.get().description;
		
		product.save();
		
		flash("success", "Product is successfully edited.");
		
		form = form.fill(product);
		return ok(adminproductedit.render(form));
	}
	
	public static Result newProductPage()
	{
		Form<Product> form = Form.form(Product.class).bindFromRequest();
		
		return ok();
	}
	
	public static Result newProduct()
	{
		Form<Product> form = Form.form(Product.class).bindFromRequest();
		Product product = form.get();
		product.save();
		flash("success", "Product Successfully added.");
		
		return ok();
	}
	
	public static Result deleteProduct(Long id)
	{
		Product.find.byId(id).delete();
		return redirect(routes.Admin.product(routes.Admin.product$default$1(),
				routes.Admin.product$default$2(), routes.Admin.product$default$3(),
				routes.Admin.product$default$4(), routes.Admin.product$default$5(),
				routes.Admin.product$default$6(), routes.Admin.product$default$7()));
	}
		
	/*
	 * Ticket
	 * Author: Uldana Mamirey
	 */
	
	public static Result ticket()
	{
		User user = User.find.where().eq("username", session().get("uname")).findUnique();
		
		List<Ticket> tickets = Ticket.find.all();
		
		return ok();
	}
	
	public static Result showTicket(Long id)
	{
		Ticket ticket = Ticket.find.byId(id);
		
		return ok();
	}
	
	public static Result replyTicket(Long id)
	{
		DynamicForm form = Form.form().bindFromRequest();
		
		Long ticketId = Long.valueOf(form.get("ticketId"));
		
		if(Ticket.find.byId(ticketId).resolved == true)
		{
			return ok();
		}
		
		if(form.get("reply") != null)
		{
			Long userId = Long.valueOf(User.find.where().eq("username", session().get("uname")).findUnique().id);
			String reply = form.get("reply");
		
			User user = User.find.byId(userId);
			Ticket ticket = Ticket.find.byId(ticketId);
			TicketMessage message = TicketMessage.create(user, reply);
		
			ticket.messages.add(message);
			ticket.save();
			flash("success", "You successfully replied.");
		}
				
		return ok();
	}
	
	public static Result deleteTicket(Long id)
	{
		Ticket ticket = Ticket.find.byId(id);
		User user = User.find.where().eq("username", session().get("uname")).findUnique();
		
		if(ticket.user.id != user.id)
		{
			flash("fail", "You don't have access to this ticket");
			return ok();
		}
		
		ticket.delete();
		
		return ok();
	}
}